using System;
using System.Web;
using System.Configuration;
using System.Web.Configuration;
using Jalal.Library.Mail;

/// <summary>
/// Summary description for SiteConfigSection
/// </summary>

namespace Jalal.Library.Web
{
    public class SiteConfigSection : ConfigurationSection
    {
        private static SiteConfigSection _siteConfig = null;
        private static string _siteName = null;

        public string SiteIP
        {
            get { return System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"].ToString(); }
        }

        public string SiteName
        {
            get { return _siteName; }
            set { _siteName = value; }
        }

        [ConfigurationProperty("encryptionKey", IsRequired = true)]
        public string EncryptionKey
        {
            get { return (string)base["encryptionKey"]; }
            set { base["encryptionKey"] = value; }
        }

        [ConfigurationProperty("connectionStringName", IsRequired = true)]
        public string ConnectionStringName
        {
            get { return (string)base["connectionStringName"]; }
            set { base["connectionStringName"] = value; }
        }

        /// <summary>
        /// Readonly property, used to read the currently selected
        /// connection string from web.config file. Which connection
        /// string is in use, is also read from the AppSettings in
        /// web.config file
        /// </summary>
        public string DBConnectionString
        {
            get
            {
                if (!string.IsNullOrEmpty(ConnectionStringName))
                {
                    // We found the current selection, so find the connection string
                    // with that name
                    ConnectionStringSettings currentConnectionString =
                        ConfigurationManager.ConnectionStrings[ConnectionStringName];

                    // If we can find the connection string then we return it
                    if (currentConnectionString != null)
                        return currentConnectionString.ConnectionString;
                }
                // If we have failed to return the connection, return null
                return null;
            }
        }

        /// <summary>
        /// Read Only property to read the site configuration from web.config
        /// </summary>
        public static SiteConfigSection SiteConfiguration
        {
            get
            {
                // If not already initialized, initialize now
                if(_siteConfig == null)
                {
                    // Read configuration form web.cofig and store it 
                    _siteConfig = (SiteConfigSection)WebConfigurationManager.GetSection("siteConfig");
                }
                // Return the settings
                return _siteConfig;
            }  
        }
    }
}
